<template>
  <div>
    <el-dialog
      v-model="visible"
      :show-close="false"
      width="1100px"
      :style="'min-height: 400px;'"
      :title="addType == 'add' ? '新建' :addType == 'edit' ? '编辑' : '查看'"
    >
      <el-form
        :model="form"
        ref="ruleFormRef"
        label-position="right"
        label-width="100px"
        :inline="true"
        :rules="rules"
        status-icon
        class="demo-form-inline"
      >
        <p class="line"><span>基本信息</span><span></span></p>

        <el-form-item label="标题:" prop="title" style="width: 92%">
          <el-input v-model="form.title" maxlength="200" placeholder="请输入" style="width: 100%" show-word-limit clearable :disabled="addType == 'look'"/>
        </el-form-item>
        <el-form-item label="父级编号:" style="width: 30%">
            <!-- <SelectOption :placeholder="'父级编号'" > </SelectOption> -->
            <el-cascader :disabled="addType == 'look'" clearable
            v-model="form.parentNumber"
            :options="data.parentNumberList"
            :show-all-levels="false"
            :props="{ value:'number', label: 'number',expandTrigger: 'hover' , checkStrictly: true }"
            @change="parentNumberChange"></el-cascader>
        </el-form-item>
        <el-form-item label="未位编号:" prop="endNumber" style="width: 30%">
          <el-input v-model="form.endNumber" :max="99"
                    maxlength="2"
                    oninput="value=value.replace(/[^0-9]/g, '')"
                    placeholder="请输入" show-word-limit
                    clearable style="width: 100%" :disabled="addType == 'look'"/>
        </el-form-item>
        <el-form-item label="类型:" prop="classType" style="width: 30%">
            <SelectOption  :options="data.classTypeList" :selectValue="form.classTypeText" @changeValue="classTypeChange" :disabled="addType == 'look'"  :placeholder="'类型'"> </SelectOption>
        </el-form-item>
<!--        <el-form-item label="计分方法:" prop="scoreMethod" style="width: 92%">-->
        <el-form-item label="计分方法:"  style="width: 92%">
          <el-input v-model="form.scoreMethod" maxlength="200" placeholder="请输入" autosize type="textarea" show-word-limit clearable  style="width: 100%" :disabled="addType == 'look'"/>
        </el-form-item>

        <p class="line" v-if="form.classType == '3' || form.classType == '4'"><span>题型规则</span><span></span></p>

        <el-form-item label="题型:" prop="questionType" style="width: 30%" v-if="form.classType == '3' || form.classType == '4'">
            <SelectOption :options="data.questionTypeList" :selectValue="form.questionTypeText" @changeValue="questionTypeChange" :disabled="addType == 'look'"> </SelectOption>
        </el-form-item>
        <el-form-item :label="form.questionType == '3' ? '填空:' : '选项:'" prop="questionItemList" v-if="form.classType == '3' || form.classType == '4'" style="width: 92%;">
          <div style="width: 100%;display: flex;flex-direction: column;">
            <el-table :data="form.questionItemList"  style="width: 100%">
                <!-- <el-table-column prop="number" label="编号" width="180"  align="center"/> -->
                <el-table-column prop="title" label="编号"  align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.number" :disabled="addType == 'look'" :max="99"
                                maxlength="2"
                                oninput="value=value.replace(/[^0-9]/g, '')"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="选项标题"  align="center">
                    <template #default="scope">
                        <el-input type="text" v-model="scope.row.title" maxlength="200" show-word-limit clearable :disabled="addType == 'look' || scope.row.itemType == 2"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="itemType" label="类型" width="100" align="center" v-show="form.questionType != '3' " :min="1" :max="99"
                                 maxlength="2"
                                 oninput="value=value.replace(/[^0-9]/g, '')">
                    <template #default="scope">
                        <span>{{ scope.row.itemType == 1 ? '选择项' : '自填选项' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="itemScore" label="分数" width="180"  align="center">
                    <template #default="scope">
                      <el-input
                        class="el-form-item__content el-select"
                        v-model="scope.row.itemScore"
                        :min="0"
                        :max="99"
                        maxlength="7"
                        oninput="value=value.replace(/[^\d.]/g, '')
                        .replace(/\.{2,}/g, '.')
                        .replace(/^(\-)*(\d+)\.(\d{4}).*$/, '$1$2.$3')
                        .replace(/^\./g, '')
                        .replace(/^0+(\d+)/, '$1')
                        .replace(/^(\d{2})\d+$/, '$1')"
                        controls-position="right"
                        :disabled="addType == 'look'"

                      />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="操作" align="center" width="100" fixed="right">
                    <template #default="{scope,$index}">
                     <el-button type="primary" @click="deleteItem($index)" v-show="addType != 'look'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 20px" v-show="addType != 'look'">
                <el-button v-if="form.questionType != '3'" @click="addItem('1')">+ 添加选择项 </el-button>
                <el-button v-if="form.questionType != '3'" @click="addItem('2')">+ 添加自填选项 </el-button>
                <el-button v-if="form.questionType == '3'" @click="addItem('3')">+ 添加填空项 </el-button>
            </div>
          </div>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="close()">关闭</el-button>
          <el-button size="small" type="primary" @click="save()" v-show="addType != 'look'">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { computed, ref, defineComponent, reactive, watch, toRefs, nextTick , onMounted} from 'vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import { ElMessage } from 'element-plus'
import * as api from "../../api/digital";
import * as proxy from '@/constants/proxy'
import { useRoute } from "vue-router";
import request from '@/utils/request'
import { getDetail } from '@/views/budget/api/hignEnd';

export default defineComponent({
  components: {SelectOption,},
  emits: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    addType: {
      type: String,
    },
    handleRowData: {
      type: Object as any,
    },
  },
  setup(props, { emit }) {
    const route = useRoute();
    const data = reactive({
        tableData:[] as any,//题型规则 选项table
        parentNumberList:[] as any,//父级编号数据列表
        classTypeList:[] as any,//编号 后的类型 一级指标 二级指标
        questionTypeList:[] as any,//题形数据
    })
    //弹出框form
    const form = reactive<any>({
       bankId:'',
        title:'',
        parentNumber:'',
        endNumber:'',
        classType:'',
        scoreMethod:'',
        questionType:'',
        questionTypeText:'',
        questionItemList:[] as any,
    })
    const visible = computed(() => {
      return props.visible;
    });
    const ruleFormRef = ref<any>();
    const rules = reactive({
        title: [
         { required: true, message: '请输入标题', trigger: 'blur' },
        ],
        parentNumber: [
         { required: true, message: '请选择父级编号', trigger: 'blur' },
        ],
        endNumber: [
         { required: true, message: '请输入未位编号', trigger: 'blur' },
        ],
        classType: [
         { required: true, message: '请选择类型', trigger: 'blur' },
        ],
        scoreMethod: [
         { required: true, message: '请输入计分方法', trigger: 'blur' },
        ],
        questionType: [
         { required: true, message: '请选择题型', trigger: 'blur' },
        ],
    })

    const close = () =>{
        // ruleFormRef.value.resetFields()
        emit('closeDialog',false)
        ruleFormRef.value.resetFields()
        form.classTypeText = ''
        form.classType = ''
        form.parentNumber = ''
        form.scoreMethod = ''
    }
    //-------
    const save = async ()  =>{
        form.bankId = route.query.bankId
         ruleFormRef.value.validate((va) =>{
            if(va){
                if(props.addType == 'add'){
                    api.saveManage(form).then(res =>{
                        if(res.data.code == 200){
                            ElMessage({
                                message: "新建成功",
                                type: "success",
                            });
                            close()
                        }

                    })
                }else{
                    Reflect.set(form, 'id', props.handleRowData.id)
                    api.updateManage(form).then(res =>{
                        if(res.data.code == 200){
                            ElMessage({
                                message: "编辑成功",
                                type: "success",
                            });
                            close()
                    }
                    })
                }
            }
         })
    }
    //题型切换
    const questionTypeChange = (item) =>{
        form.questionType = item.itemValue
        form.questionTypeText = item.itemText
    }
    //类型切换
    const classTypeChange = (item) =>{
        form.classType = item.itemValue
        form.classTypeText = item.itemText
    }
    //父级编号的数据
    const getFaNumber = () =>{
        api.getFaNumber({bankId:route.query.bankId}).then(res =>{
            console.log('父级编号',res.data.data);
            getTypeList(res.data.data);
            data.parentNumberList = res.data.data
        })
    }
    // 处理数据，判断数据children是否有数据
     const getTypeList = (listData) => {
       listData.forEach((items) => {
          if (items.children.length > 0) {
            getTypeList(items.children)
          } else {
            items.children = undefined
          }
       })
     }
     //添加选择项
     const addItem = (val) =>{
        let obj = {
            number : (form.questionItemList && form.questionItemList.length) ? +form.questionItemList[form.questionItemList.length - 1].number + 1 as any :  1,
            title: '',
            itemType: val,
            itemScore: undefined,
        }
        if(val == '2'){
          obj.title = '其它'
        }
        form.questionItemList.push(obj)
        console.log('form',form,form.questionItemList);

     }
     //删除选择
     const deleteItem = (i) =>{
        form.questionItemList.splice(i,1)
     }

    //父级编号选择时
    const parentNumberChange = (val) =>{
        form.parentNumber = val[val.length - 1]
        console.log('父级编号选择',form.parentNumber);
    }
    // 字典
    const affiliation = () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data:["KHGL_DE_QUESTION_TYPE_CODE","KHGL_DE_QUESTION_ITEM_TYPE_CODE","KHGL_DE_INDEX_TYPE_CODE"]

      }).then((res) => {
        console.log('字典',res);
        data.classTypeList = res.data.data.KHGL_DE_INDEX_TYPE_CODE
        data.questionTypeList = res.data.data.KHGL_DE_QUESTION_TYPE_CODE
      })
    }

    const resetFormMyself = () => {
        Object.assign(form, {})
    }

    const myForm = reactive<any>({ ...form });

    watch(() => props.visible,(newval) => {
        if (newval) {
        getDetailForm()
        getFaNumber()

        nextTick(() => {
           //初始绑定需在form完成初始化\
            ruleFormRef.value?.resetFields();
            form.questionItemList = []
            form.classType = ''
            resetFormMyself(); //当form表单一开始是v-if隐藏时就不能清空，需额外单独清空

        });
        }
      }
    );
    const getDetailForm = () =>{
        if(props.addType != 'add'){
            api.detailManage({id:props.handleRowData.id}).then(res =>{
                console.log('detail',res.data.data);
                let da = res.data.data
                // Object.assign(form,da)

                for (let k in form) {
                    if(da[k]){
                        form[k] = da[k]
                    }
                }

                data.classTypeList.forEach(e => {
                    if(e.itemValue == form.classType){
                        form.classTypeText = e.itemText
                    }
                })
                data.questionTypeList.forEach(e => {
                    if(e.itemValue == form.questionType){
                        form.questionTypeText = e.itemText
                    }
                })

                // form.title = da.title,
                // form.parentNumber =  da.parentNumber,
                // form.endNumber =  da.endNumber,
                // form.classType =  da.classType,
                // form.scoreMethod =  da.scoreMethod,
                // form.questionType =  da.questionType,
                // form.questionTypeText =  da.questionTypeText,
                // form.questionItemList =  da.questionItemList,
            })
        }
    }
    onMounted(() =>{
        affiliation()
    })
    return {
      form,
      close,
      save,
      rules,
      data,
      parentNumberChange,
      affiliation,
      addItem,
      deleteItem,
      questionTypeChange,
      classTypeChange,
      visible,
      ruleFormRef,
    }
  },
})
</script>

<style lang="scss" scoped>
.line{
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 18px;
    color: #409eff;
    span:last-of-type{
            // width: 100%;
            flex: 1;
            height: 0;
            border-top: 1px solid ;
            border-color: #ccc;
            margin-left: 15px;
        }
}
</style>
